package cn.bx.bid.ctrl;

import cn.bx.bid.config.MailConfig;
import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.User;
import cn.bx.bid.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.UUID;

@RestController
//@RequestMapping("/user")
@Api(value = "用户模块")
public class UserController {
    private static final Logger Log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @Autowired
    private MailConfig mailConfig;

    @Value("${bid.savefilepath}")
    private String fileSavePath;

    @ApiOperation(value = "用户登录",notes = "根据用户名和密码登录")
    @RequestMapping(value = "ulogin",method = {RequestMethod.GET,RequestMethod.POST})// user/login
    @ResponseBody
    public Map<String, Object> login(@RequestParam("username") String u, @RequestParam("password") String p, HttpSession s) {
        User user = userService.login(u, p);

        if (user != null)
            s.setAttribute("USER_LOGIN", u);
        Map<String, Object> m = new HashMap<>();
        m.put("msg", user != null);
        m.put("obj", user);
        return m;
        //out.flush();
//        if(user==null){
//            return "/login.jsp";
//        }
//        s.setAttribute("USER_LOGIN",user);
//        //session中存入用户信息
//        //return "welcome.jsp";//默认是转发
//        return "redirect:/welcome.jsp";
    }

    //    @RequestMapping("usersearch")
//    public ModelAndView paging(@RequestParam(value="pageNo",defaultValue = "1") int pageNo, @RequestParam(value="limit",defaultValue = "10") int limit, @RequestParam(value = "name",required = false) String name, @RequestParam(value = "start",required = false)Date start, @RequestParam(value = "end",required = false)Date end){
//        ModelAndView mv=new ModelAndView();
//        mv.addObject("name",name);
//        mv.addObject("pageNo",pageNo);
//        mv.addObject("p",this.userService.paging(pageNo,limit,name,start,end));
//        mv.setViewName("userlist");//.jsp
//        return mv;
//    }
    @ApiOperation(value = "用户搜索",notes = "用户搜索")
    @RequestMapping("userSearch")
    @ResponseBody
    public Page<User> paging2(@RequestParam(value = "page", defaultValue = "1") int pageNo, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "startDate", required = false) Date start, @RequestParam(value = "endDate", required = false) Date end) {
        System.out.println(">>><><>??>?><"+mailConfig);
        return this.userService.paging(pageNo, limit, name, start, end);
    }

    //u还在上下文中，叫u
    //文件域的名称不能和对象中的属性重复
    //目录是临时目录中
//    @RequestMapping("useradd")
//    public String add(@ModelAttribute("u") User u, @RequestParam("idcard") MultipartFile f, @RequestParam("idcard2") MultipartFile f2,HttpSession s){
//        Log.info(">>>>>>>>>>>"+ fr.length);
//        for(MultipartFile f:fr){
//            if(f.isEmpty()==false){
//                String tname=f.getOriginalFilename();
//                Log.debug(">>>>>原始文件名："+tname+"...."+f.getName());
//                String suffix=tname.substring(tname.lastIndexOf('.'));
//                String newFileName= UUID.randomUUID()+suffix;
//                if(f.getName().equals("idcard"))
//                    u.setZhengmian(newFileName);
//                else if(f.getName().equals("idcard2"))
//                    u.setFanmian(newFileName);
//
//                String rootpath=s.getServletContext().getRealPath("images");
//
//                Log.debug(">>>>>位置"+rootpath);
//                try {
//                    File temp=new File(rootpath);
//                    if(!temp.exists())
//                        temp.mkdirs();
//                    f.transferTo(new java.io.File(temp,newFileName));
//                } catch (IOException e) {
//                    Log.error("上传文件失败",e);
//                }
//            }
//        }
//        this.userService.add(u);
//        return "redirect:/usersearch.jhtml";
//    }
    @ApiOperation(value = "用户添加",notes = "用户添加")
    @RequestMapping(value="useradd",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String add(@ModelAttribute("u") User u, @RequestParam("idcard2") MultipartFile f, HttpSession s) {
        if (f.isEmpty() == false) {
            String tname = f.getOriginalFilename();
            Log.debug(">>>>>原始文件名：" + tname + "...." + f.getName());
            String suffix = tname.substring(tname.lastIndexOf('.'));
            String newFileName = UUID.randomUUID() + suffix;
            String rootpath =fileSavePath; //s.getServletContext().getRealPath("images");

            //Log.i(">>>>>位置" + rootpath);
            try {
                File temp = new File(rootpath);
                Log.info(">>>>>位置" + temp.getAbsolutePath());
                if (!temp.exists())
                    temp.mkdirs();
                f.transferTo(new File(temp, newFileName));
                u.setIdcard(newFileName);
            } catch (IOException e) {
                Log.error("上传文件失败", e);
            }
        }
        this.userService.add(u);
        return "{\"result\":true}";
    }

    @ApiOperation(value = "用户删除",notes = "restful 方法删除用户")
    @RequestMapping("userdel-{id}")
    @ResponseBody
    public String del(@PathVariable("id") long id) {
        int r = this.userService.batchDel(new long[]{id});
        return "{\"msg\":" + (r > 0) + "}";
    }

    @RequestMapping("batchDel")
    @ResponseBody
    public String batchDel(@RequestParam("id[]") long[] id) {
        int r = this.userService.batchDel(id);
        return "{\"msg\":" + (r > 0) + "}";
        // rd.addFlashAttribute("msg",r>0?"删除成功":"删除失败");//显示后自动删除
        //return "redirect:/usersearch.jhtml";
    }

    //    @RequestMapping("useradd2")
//    public String add2(@RequestParam Map u){
//        //InternalResourceViewResolver v=
//       // Model m=null;
//
//        System.out.println(u+">>>>>>>>>>>>>>>>");
//        return "redirect:/usersearch.jhtml";
//    }
//    @RequestMapping("useradd")
//    public void add(@ModelAttribute("u") User u, Writer out){
//       /* CharacterEncodingFilter f=null;
//        f.setForceEncoding(true);
//        f.setEncoding("utf-8");*/
//        this.userService.add(u);
//        //return "redirect:/usersearch.jhtml";
//        try {
//            out.append("<script>alert('add success');location.replace('usersearch.jhtml')</script>");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // return null;
//    }
    @InitBinder
    public void init(WebDataBinder binder) {
        CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }

}
